package com.middleware.mvc.loaders;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletContext;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WebXmlServletLoader {

    private  static  Map<String, String> servletMappings = new HashMap<>();

    public static void setServletMappings(Map<String, String> servletMappings){
        WebXmlServletLoader.servletMappings = servletMappings;
    }
    public static Map<String, String> parseWebXmlServletMappings(ServletContext context) {
        Map<String, String> servletMappings = new HashMap<>();
        String webXmlPath = context.getRealPath("/WEB-INF/web.xml");

        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(webXmlPath));
            // 使用XPath查询所有servlet-mapping
            List<Node> mappings = document.selectNodes("//*[local-name()='servlet-mapping']");
            for (Node mappingNode : mappings) {
                Element mappingElement = (Element) mappingNode;
                String servletName = mappingElement.elementText("servlet-name");
                String urlPattern = mappingElement.elementText("url-pattern");
                servletMappings.put(servletName, urlPattern);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return servletMappings;
    }

    public Map<String, String> getServletMappings() {
        return servletMappings;
    }
    public static String getValue(String servletName) {
        return servletMappings.get(servletName);
    }
}
